﻿using System.Data.Entity;
using System.Data.Entity.Database;
using Example.Entities;

namespace Example.Model
{
    /// <summary>
    /// Databse context.
    /// </summary>
    public class ModelContext : DbContext
    {
        static ModelContext()
        {
            DbDatabase.SetInitializer(new DatabaseInitializer());
        }

        /// <summary>
        /// Creates new instance of ModelContext.
        /// </summary>
        public ModelContext()
        {
        }

        /// <summary>
        /// Additional mappings and entities configurations.
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // cant put this into entity itself, because it would show error for IDataErrorInfo validation
            modelBuilder.Entity<Order>().HasRequired(x => x.Owner);
        }

        /// <summary>
        /// Customers set.
        /// </summary>
        public DbSet<Customer> Customers { get; set; }

        /// <summary>
        /// Orders set.
        /// </summary>
        public DbSet<Order> Orders { get; set; }
    }

    /// <summary>
    /// Allows us to initialize defaults when database is recreated.
    /// </summary>
    public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<ModelContext>
    {
        protected override void Seed(ModelContext context)
        {
            base.Seed(context);            
        }
    }
}
